import { HttpError, toSuccess, useEntityManager } from "@sker/core";
import { AutoUser, KsDevice, KsLiveRoomLog } from "@sker/entities";
import { useData } from "@sker/runtime";
import dayjs from "dayjs";
import { z } from "zod";


export default async () => {
    const input = z.object({
        token: z.string(),
        id: z.any()
    });
    const body = input.parse(useData())

    return await useEntityManager(async m => {
        const user = await m.findOne(AutoUser, { where: { token: body.token } })
        if (!user) throw new HttpError(`请重新登录`)
        if (user.replace_mobile) user.mobile = user.replace_mobile
        const device = await m.findOne(KsDevice, { where: { id: parseInt(body.id) } })
        if (!device) {
            throw new HttpError(`请输入正确的设备编号`)
        }
        if (device.owner !== user.mobile) {
            throw new HttpError(`设备有误`)
        }
        const setting = device.setting;
        const useTime = Math.floor((dayjs().toDate().getTime() - dayjs().startOf('hour').toDate().getTime()) / (1000 * 60));
        let successCount: number = 0;
        let money: number = 0;
        let total: number = 0;
        let open_time: string = dayjs().format('HH:mm:ss')
        const qb = await m.createQueryBuilder()
            .select("count(1)", "success")
            .addSelect("sum(log.count)", "money")
            .from(KsLiveRoomLog, 'log')
            .where('log.uuid=:uuid', { uuid: device.uuid })
            .andWhere('log.open_time>=:start_time', { start_time: dayjs().startOf('hour').toDate() })
            .andWhere('log.open_time<=:end_time', { end_time: dayjs().endOf('hour').toDate() })
            .andWhere('log.count>:count', { count: 0 })
            .execute()
        if (qb && qb.length > 0) {
            const item = qb[0]
            successCount = parseInt(item.success)
            money = parseInt(item.money)
            open_time = dayjs(item.open_time).format('HH:mm:ss')
        }
        const totalQb = await m.createQueryBuilder()
            .select("count(1)", "total")
            .addSelect("max(log.open_time)", "open_time")
            .from(KsLiveRoomLog, 'log')
            .where('log.uuid=:uuid', { uuid: device.uuid })
            .andWhere('log.open_time>=:start_time', { start_time: dayjs().startOf('hour').toDate() })
            .andWhere('log.open_time<=:end_time', { end_time: dayjs().endOf('hour').toDate() })
            .execute()
        if (totalQb && totalQb.length > 0) {
            const item = totalQb[0]
            total = parseInt(item.total || 0)
        }
        return toSuccess({ id: device.id, status: setting.status || 'start', stopTime: setting.stopTime, useTime, successCount, money, total, open_time })
    })
}
